import json
import pymongo
import time
from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from bson import json_util
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.contrib.auth import login,authenticate

#配置数据库连接

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["test3"]

mycoldl = mydb["dlhistory"] #下载的历史记录

#根据前端url传来的数据，判断当前问卷类别，返回相应的问卷与草稿箱数据库以及查询信息
def getMycol(no):
    if no == 'no1':
        return {
            'mycol':mydb["questionnaire1"],  # 存储脑出血患者调查问卷
            'mycol1':mydb["questionnaire11"],  # 草稿箱中的脑出血患者调查问卷存储
            'wen':'wenjuan1',
            'no':'no11'

        }
    elif no == 'no2':
        return {
            'mycol':mydb["questionnaire2"],  # 存储健康人群调查问卷
            'mycol1':mydb["questionnaire12"], # 草稿箱中的健康人群调查问卷存储
            'wen':'wenjuan2',
            'no':'no12'
        }
    elif no == 'no4':
        return {
            'mycol':mydb["questionnaire4"],  # 存储健康人群调查问卷(体检中心)
            'mycol1':mydb["questionnaire14"],  # 草稿箱中的健康人群调查问卷(体检中心)存储
            'wen':'wenjuan4',
            'no':'no14'
        }
    elif no == 'no5':
        return {
            'mycol':mydb["questionnaire5"],  # 存储脑出血患者调查问卷(医院)
            'mycol1':mydb["questionnaire15"],  # 草稿箱中的脑出血患者调查问卷(医院)存储
            'wen':'wenjuan5',
            'no':'no15'
        }
    elif no == 'no6':
        return {
            'mycol':mydb["questionnaire6"], # 存储随访问卷
            'mycol1':mydb["questionnaire16"],  # 草稿箱中的随访问卷存储
            'wen':'wenjuan6',
            'no':'no16'
        }
    elif no == 'no7':
        return {
            'mycol':mydb["questionnaire7"],  # 存储入户筛查表
            'mycol1':mydb["questionnaire17"],  # 草稿箱中的入户筛查表存储
            'wen':'wenjuan7',
            'no':'no17'
        }
    elif no == 'no8':
        return {
            'mycol':mydb["questionnaire8"],  
            'mycol1':mydb["questionnaire18"],  
            'wen':'wenjuan8',
            'no':'no18'
        }
    elif no == 'no9':
        return {
            'mycol':mydb["questionnaire9"],  
            'mycol1':mydb["questionnaire19"],  
            'wen':'wenjuan9',
            'no':'no19'
        }
    elif no == 'no10':
        return {
            'mycol': mydb["questionnaire10"],
            'mycol1': mydb["questionnaire110"],
            'wen': 'wenjuan10',
            'no': 'no110'
        }
    else:
        return {
            'mycol': mydb["questionnaire011"],
            'mycol1': mydb["questionnaire111"],
            'wen': 'wenjuan11',
            'no': 'no111'
        }


#判断省各省名称
def getProvince(province):
    if province == 'hunan':
        return '湖南省'
    elif province == 'hubei':
        return '湖北省'
    elif province == 'henan':
        return '河南省'
    elif province == 'anhui':
        return '安徽省'
    else:
        return '江西省'


#各省草稿箱记录选择页面
@login_required
def wenjuancgx_index(request,province):
    return render(request, "wenjuancgx/"+province+"/index.html")

#各省草稿箱记录
@login_required
def wenjuancgx(request,province,no):
    my = getMycol(no)
    wen = my['wen']
    # 从json文件中读取json数据
    file_path = "D:/Project/ncx/Ncx-Management-System/Ques/static/json/"+wen+".json"
    with open(file_path, 'r', encoding='UTF-8') as f:
        wenjuan_content = json.load(f)

    return render(request, 'wenjuancgx/'+province+'/'+wen+'_cgx.html', {"excelTitle": json_util.dumps(list(wenjuan_content))})

#各省草稿箱记录数据请求处理
@login_required
def wenjuancgx_solve(request,province,no): #脑出血患者调查手册分页查询
    my = getMycol(no)
    mycol1 = my['mycol1']
    province1 = getProvince(province)
    page = request.POST.get("page")  # 取得当前页数，注意这是jqgrid自身的参数
    rows = request.POST.get("rows")  # 取得每页显示行数，注意这是jqgrid自身的参数

    questionnaire = []

    totalRecord = mycol1.find({"所在的省": province1}).count()  # 总记录数(应根据数据库取得,在此只是模拟)

    for x in mycol1.find({"所在的省": province1}, {'_id': 1, '填表人签名': 1, '填表人联系电话': 1, '填表人填写日期': 1}).skip((int(page) - 1) * int(rows)).limit(int(rows)):
      
        x['填表人联系电话'] = x['填表人联系电话'][0:6] + '****'   
        questionnaire.append(x)


    if totalRecord % int(rows) == 0:  # 计算总页数
        totalPage = int(totalRecord / int(rows))
    else:
        totalPage = int(totalRecord / int(rows)) + 1


    # 构造jqGrid接受的json数据格式
    json = {
        "page": page,
        "total": totalPage,
        "records": totalRecord,
        "rows": questionnaire
    }

    return HttpResponse(json_util.dumps(json))  # answer的第一条记录为question

# 湖南省专用草稿箱记录数据请求处理
@login_required
def wenjuancgx_hunan_solve(request, no):  # 脑出血患者调查手册分页查询
    my = getMycol(no)
    mycol1 = my['mycol1']
    page = request.POST.get("page")  # 取得当前页数，注意这是jqgrid自身的参数
    rows = request.POST.get("rows")  # 取得每页显示行数，注意这是jqgrid自身的参数

    questionnaire = []

    postData = request.POST.get("postData")
    postDatas = str(postData).split()

    if not postData:
        totalRecord = mycol1.find({}).count()  # 总记录数(应根据数据库取得,在此只是模拟)
        for x in mycol1.find({}, {'_id': 1, '填表人签名': 1, '填表人联系电话': 1, '填表人填写日期': 1}
                             ).skip((int(page) - 1) * int(rows)).limit(int(rows)):
            x['填表人联系电话'] = x['填表人联系电话'][0:7] + '****'
            questionnaire.append(x)
    else:
        conditions = {}
        condition = [{"$or": [{"_id": {'$regex': postDatas[0]}},
                              {"填表人签名": {'$regex': postDatas[0]}},
                              {"填表人联系电话": {'$regex': postDatas[0]}},
                              {"填表人填写日期": {'$regex': postDatas[0]}}]}]
        for p in postDatas[1:]:
            new_condition = {"$or": [{"_id": {'$regex': p}},
                                     {"填表人签名": {'$regex': p}},
                                     {"填表人联系电话": {'$regex': p}},
                                     {"填表人填写日期": {'$regex': p}}]}
            condition.append(new_condition)
        conditions.update({"$and": condition})
        totalRecord = mycol1.find(conditions).count()  # 总记录数(应根据数据库取得,在此只是模拟)
        for x in mycol1.find(conditions, {'_id': 1, '填表人签名': 1, '填表人联系电话': 1, '填表人填写日期': 1}).skip(
                (int(page) - 1) * int(rows)).limit(int(rows)):
            x['填表人联系电话'] = x['填表人联系电话'][0:7] + '****'
            questionnaire.append(x)

    if totalRecord % int(rows) == 0:  # 计算总页数
        totalPage = int(totalRecord / int(rows))
    else:
        totalPage = int(totalRecord / int(rows)) + 1

    # 构造jqGrid接受的json数据格式
    json = {
        "page": page,
        "total": totalPage,
        "records": totalRecord,
        "rows": questionnaire
    }

    return HttpResponse(json_util.dumps(json))  # answer的第一条记录为question

@login_required
def ExportWenjuancgx(request, user, no):
    my = getMycol(no)
    mycol1 = my['mycol1']
    wen = my['wen']
    answer = []
    # print(request.POST)  # 输出被django处理过的数据形式
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    # 从json文件中读取json数据
    file_path = "D:/Project/ncx/Ncx-Management-System/Ques/static/json/"+wen+".json"
    with open(file_path, 'r', encoding='UTF-8') as f:
        wenjuan_content = json.load(f)

    for id in tj:
        for x in mycol1.find({"_id": id}, {"_id": 0}):
            # {**excelTitle,**x}:Python3中两字典的合并与更新,使得导出问卷excel的表头是一致的,同时把调查问卷json的所有value都转换成字符串，这样就能保证导出excel没有数据缺失
            # answer.append(list({**wenjuan5_content,**x}.values()))
            answer.append([str(i) for i in list({**wenjuan_content, **x}.values())])

    no1 = my['no']
    mycoldl.insert({"问卷记录": no1, "用户": user, "条数": len(tj), "具体信息": selectRaw,
                    "时间": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))})  # 使用dlhistory存储用户下载历史
    return HttpResponse(json_util.dumps(answer))  # answer的第一条记录为question

  

@login_required
def DelWenjuan1_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol11.delete_one({"_id": id})

    for x in mycol11.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功


@login_required
def DelWenjuan2_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol12.delete_one({"_id": id})

    for x in mycol12.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功


@login_required
def DelWenjuan4_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol14.delete_one({"_id": id})

    for x in mycol14.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan5_cgx(request): #删除基线脑出血患者问卷（医院）中的调查记录
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol15.delete_one({"_id":id})

    for x in mycol15.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功



@login_required
def DelWenjuan6_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol16.delete_one({"_id":id})

    for x in mycol16.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功


@login_required
def DelWenjuan7_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol17.delete_one({"_id":id})

    for x in mycol17.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan8_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol18.delete_one({"_id":id})

    for x in mycol18.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan9_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol19.delete_one({"_id":id})

    for x in mycol19.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功
@login_required
def DelWenjuan10_cgx(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol110.delete_one({"_id":id})

    for x in mycol110.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功